import { merge } from 'lodash-es'

import { useGlobalSetting } from '@/settings/system'
import { buildUrl } from '@/utils/tools'

export interface CarryData {
  queryData?: AnyObject
  extraData?: AnyObject
}

export interface MiniAppIdInfo {
  appId?: string
  /**
   * 'develop': 开发版;
   * 'trial': 体验版;
   * 'release': 正式版;
   */
  envVersion?: 'develop' | 'trial' | 'release'

  path?: string
}

export function openMiniAppHelper(data?: CarryData, options?: MiniAppIdInfo) {
  const { isDev } = useGlobalSetting()
  const newOptions = merge(
    {
      appId: 'wx2aa37f9939b04166',
      envVersion: isDev ? 'trial' : 'release',
      path: '/pages/auth/index'
    },
    options
  )
  if (data?.queryData)
    newOptions.path = buildUrl(newOptions.path, data.queryData)

  if (canIUseEmbedded()) {
    return wx.openEmbeddedMiniProgram({
      ...newOptions,
      ...data
    })
  } else {
    uni.navigateToMiniProgram({
      ...newOptions,
      ...data
    })
  }
}

function canIUseEmbedded() {
  const { SDKVersion } = uni.getSystemInfoSync()
  const arr = SDKVersion.split('.')
  console.log('SDKVersion: ', SDKVersion)
  return Number(arr[0]) >= 2 && Number(arr[1]) >= 23 && Number(arr[2]) >= 1
}
